<template>
  <div class="house">
    <div class="tag" style="margin-bottom: 1vw">
      大棚信息
    </div>
    <div class="container">
      <div v-for="(item, index) in greenhouseData" :key="index" class="box">
        <div class="title">{{ item.title }}</div>
        <div class="value">{{ item.value }}</div>
        <div ref="chart" class="chart"></div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import axios from 'axios';
import { useStore } from '@/store/index.js';

export default {
  name: 'House',
  props: {
    greenhouseId: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      greenhouseData: [], // 初始化为空数组
      chartInstances: [], // 存储echarts实例
    };
  },
  async mounted() {
    await this.fetchGreenhouseData(); // 获取数据
    this.initCharts(); // 初始化图表
  },
  beforeUnmount() {
    // 清理所有echarts实例
    this.chartInstances.forEach(chart => {
      if (chart) {
        chart.dispose();
      }
    });
    this.chartInstances = [];
  },
  watch: {
    // 监听 greenhouseId 变化，重新获取数据
    greenhouseId(newId) {
      this.fetchGreenhouseData();
    }
  },
  methods: {
    // 获取大棚数据
    async fetchGreenhouseData() {
      try {
        const userStore = useStore();
        const token = userStore.token;
        
        // 根据传入的 greenhouseId 获取对应的大棚数据
        const response = await axios.get(`/api/house/${this.greenhouseId}`, {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        });
        const greenhouse = response.data;

        // 将 API 返回的数据映射到 greenhouseData
        if (greenhouse) {
          this.greenhouseData = [
            {title: '大棚编号', value: greenhouse.id},
            {title: '大棚名称', value: greenhouse.name},
            {title: '面积', value: `${greenhouse.area} 平方米`},
            {title: '地址', value: greenhouse.address},
          ];
        }
      } catch (error) {
        console.error('Error fetching greenhouse data:', error);
        // 如果获取失败，尝试从所有大棚中获取第一个
        this.fallbackFetchData();
      }
    },

    // 备用方案：获取所有大棚数据
    async fallbackFetchData() {
      try {
        const userStore = useStore();
        const token = userStore.token;
        const response = await axios.get('/api/house/all', {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        });
        const data = response.data;

        if (data.length > 0) {
          const greenhouse = data.find(g => g.id === this.greenhouseId) || data[0];
          this.greenhouseData = [
            {title: '大棚编号', value: greenhouse.id},
            {title: '大棚名称', value: greenhouse.name},
            {title: '面积', value: `${greenhouse.area} 平方米`},
            {title: '地址', value: greenhouse.address},
          ];
        }
      } catch (error) {
        console.error('Fallback fetch also failed:', error);
      }
    },

    // 初始化图表
    initCharts() {
      // 先清理旧实例
      this.chartInstances.forEach(chart => {
        if (chart) {
          chart.dispose();
        }
      });
      this.chartInstances = [];
      
      const charts = document.querySelectorAll('.chart');
      charts.forEach((chart) => {
        const echartInstance = echarts.init(chart);
        this.chartInstances.push(echartInstance); // 保存实例引用
        const option = {
          series: [
            {
              type: 'gauge',
              startAngle: 90,
              endAngle: -270,
              radius: '100%',
              pointer: {
                show: false,
              },
              progress: {
                show: true,
                overlap: true,
                roundCap: true,
                clip: false,
                itemStyle: {
                  borderWidth: 1,
                  borderColor: '#00ffcc',
                },
              },
              axisLine: {
                lineStyle: {
                  width: 20,
                  color: [
                    [1, '#00ffcc'],
                  ],
                },
              },
              splitLine: {
                show: false,
              },
              axisLabel: {
                show: false,
              },
              anchor: {
                show: false,
              },
              detail: {
                show: false,
              },
              data: [
                {
                  value: 100,
                },
              ],
            },
          ],
        };
        echartInstance.setOption(option);
      });
    },
  },
};
</script>

<style>
.house {
  justify-content: center;
  align-items: center;
  margin-right: 1.5vw;
}

.container {
  display: grid;
  grid-template-columns: repeat(4, 1fr); /* 设置为 4 列布局 */
  gap: 1vw; /* 列间距 */
  width: 100%; /* 容器宽度调整 */
  margin-bottom: 1vw;
}

.tag {
  text-align: center;
  font-size: 1vw; /* 调小字体 */
  font-weight: bold;
  color: #00eaff;
  text-shadow: 0px 0px 8px #00eaff; /* 标题发光效果 */
  margin-bottom: 1vw;
}
.box {
  position: relative;
  background: linear-gradient(135deg, #1f1f1f, #333);
  border: 1px solid rgb(37, 95, 180);
  border-radius: 10px;
  box-shadow: 0 0 10px rgb(40, 134, 234);
  padding: 10px; /* 缩小内边距  */
  width: 100%;
  height: 100px; /* 调整高度 */
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  text-align: center;
}

.title {
  font-size: 16px; /* 字体缩小 */
  color: #c7bdc0;
  margin-bottom: 8px;
}

.value {
  font-size: 15px; /* 字体缩小 */
  font-weight: bold;
  color: #fff;
}

.chart {
  position: absolute;
  bottom: -15px;
  width: 80px; /* 速缩小图表宽度 */
  height: 40px; /* 缩小图表高度 */
}
</style>